package com.test.a48;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Component;

/****
 *  事件解耦例子
 * ApplicationListener 实现接口来实现监听
 * 一  创建事件对象
 * 二 发事件
 * 三、事件监听
 * @author Administrator
 *
 */
@Configuration
public class A48_1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48_1.class);
        context.getBean(MyService.class).doBusiness();
        context.close();
    }

    
    /****
     * 一、创建一个事件对象   需要继承ApplicationEvent
     * @author Administrator
     *
     */
    static class MyEvent extends ApplicationEvent {
        public MyEvent(Object source) {  //需要加带参数构造
            super(source);
        }
    }

    /***
     * 业务类  发送事件
     * @author Administrator
     *
     */
    @Component
    static class MyService {
        private static final Logger log = LoggerFactory.getLogger(MyService.class);
        @Autowired
        private ApplicationEventPublisher publisher; //相当于 applicationContext 事件发布器
        public void doBusiness() {
            log.debug("主线业务");
            // 二  主线业务完成后需要做一些支线业务，下面是问题代码   
            publisher.publishEvent(new MyEvent("MyService.doBusiness()"));   //发布事件  MyEvent
        }
    }

    /****
     * ApplicationListener<MyEvent  事件监听器  监听MyEvent对象
     * @author Administrator
     *
     */
//    @Component
    static class SmsApplicationListener implements ApplicationListener<MyEvent> {
        private static final Logger log = LoggerFactory.getLogger(SmsApplicationListener.class);
        @Override
        public void onApplicationEvent(MyEvent event) {
            log.debug("发送短信");
        }
    }

    /****
     *  事件监听器  监听MyEvent对象
     * @author Administrator
     *
     */
    @Component
    static class EmailApplicationListener implements ApplicationListener<MyEvent> {
        private static final Logger log = LoggerFactory.getLogger(EmailApplicationListener.class);
        @Override
        public void onApplicationEvent(MyEvent event) {
            log.debug("发送邮件");
        }
    }

}